package com.kly.module_base.base

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import androidx.viewbinding.ViewBinding
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.*
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider


/**
 * @ClassName: BaseDialog
 * @Description:
 * @Author: You
 */
abstract class BaseDialog<Binding : ViewBinding, ViewModel : BaseViewModel>(private val inflaterBlock: (LayoutInflater) -> Binding, private val modelClass: Class<ViewModel>) : DialogFragment() {
    var binding: Binding? = null
    var mViewModel: ViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (getStyle() != 0) {
            setStyle(STYLE_NORMAL, getStyle())
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (binding == null) {
            binding = inflaterBlock(layoutInflater)
            val widthAndHeightPercent = getWidthAndHeightPercent()
            when {
                widthAndHeightPercent.size >= 2 -> {
                    setDialogSize(widthAndHeightPercent[0], widthAndHeightPercent[1])
                }
                widthAndHeightPercent.size == 1 -> {
                    setDialogSize(widthAndHeightPercent[0], 1.0f)
                }
                else -> {
                    setDialogSize(1.0f, 1.0f)
                }
            }
        }
        return binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mViewModel = ViewModelProvider(requireActivity())[modelClass]

        dialog?.let {
            it.setCanceledOnTouchOutside(getCanceledOnTouchOutside())
            it.setOnKeyListener { _: DialogInterface?, _: Int, _: KeyEvent? -> getCanceled() }
            if (getWindowAnimations() != 0) {
                it.window?.setWindowAnimations(getWindowAnimations())
            }
            //设置导航栏颜
//            it.window?.navigationBarColor = Color.TRANSPARENT
//            //内容扩展到导航栏
//            it.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL)
        }

        initData()
        initListener()
    }

    open fun initListener() {

    }

    abstract fun initData()

    @SuppressLint("UseRequireInsteadOfGet")
    fun show(manager: Any, tag: String? = "") {
        when (manager) {
            is FragmentActivity -> {
                setFragmentManager(manager.supportFragmentManager, tag)
            }
            is Fragment -> {
                setFragmentManager(manager.parentFragmentManager, tag)
            }
            else -> {
                throw IllegalArgumentException("not is FragmentManager")
            }
        }
    }

    /**
     * 显示DialogFragment
     */
    private fun setFragmentManager(manager: FragmentManager, tag: String? = "") {
        try {
            manager.beginTransaction().remove(this).commitAllowingStateLoss()
            super.show(
                manager, if (tag.isNullOrBlank()) {
                    System.currentTimeMillis().toString()
                } else {
                    tag
                }
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 设置显示屏幕大小
     */
    private fun setDialogSize(widthPercent: Float, heightPercent: Float) {
        val dm = DisplayMetrics()
        val activity = activity
        val dialog: Dialog? = dialog
        if (activity != null && dialog != null) {
            activity.windowManager.defaultDisplay.getMetrics(dm)
            val window: Window? = dialog.window
            if (window != null) {
                window.decorView.setPadding(0, 0, 0, 0)
                val lp: WindowManager.LayoutParams = window.attributes
                lp.width = if (widthPercent == 0f) WindowManager.LayoutParams.WRAP_CONTENT else if (widthPercent == 1f) WindowManager.LayoutParams.MATCH_PARENT else (dm.widthPixels * widthPercent).toInt()
                lp.height = if (heightPercent == 0f) WindowManager.LayoutParams.WRAP_CONTENT else if (heightPercent == 1f) WindowManager.LayoutParams.MATCH_PARENT else (dm.heightPixels * heightPercent).toInt()
                window.attributes = lp
                window.setBackgroundDrawable(ColorDrawable())
            }
        }
    }


    /**
     * 其他区域是否点击消失
     * @return 默认false，不消失
     */
    open fun getCanceledOnTouchOutside(): Boolean = false

    /**
     * 显示动画
     */
    open fun getWindowAnimations(): Int = 0

    /**
     * 屏蔽返回键
     * @return 默认true，屏蔽
     */
    open fun getCanceled(): Boolean = true

    /**
     * 设置Style
     * @return 风格
     */
    open fun getStyle(): Int = 0

    /**
     * 获取DialogFragment的宽高
     */
    open fun getWidthAndHeightPercent(): MutableList<Float> = mutableListOf(1.0f, 1.0f)
}